package com.demo.boss.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.demo.boss.common.convert.UserConvert;
import com.demo.boss.common.enums.SysCode;
import com.demo.boss.entity.UserInfo;
import com.demo.boss.models.PageRequest;
import com.demo.boss.models.Result;
import com.demo.boss.models.request.UserEditRequest;
import com.demo.boss.models.vo.UserInfoVo;
import com.demo.boss.server.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private UserConvert userConvert;

    /**
     * 查询商户信息
     */
    @GetMapping("/merch/pageList")
    public Result pageList(@Validated PageRequest pageRequest) {
        // 调用 userService 分页查询 mybatis-plus 有分页插件功能
        IPage<UserInfo> pageResult = userService.queryPageList(pageRequest);

        long pages = pageResult.getPages(); // 总页数
        long current = pageResult.getCurrent(); // 页号
        List<UserInfo> userInfoList = pageResult.getRecords(); // 分页结果
        Map<String, Object> data = new HashMap<>();
        data.put("current", current);
        data.put("pages", pages);
        data.put("list", userConvert.convertListInfoVo(userInfoList));
        return Result.ok(data);
    }

    /**
     * 新增或修改商户信息操作
     */
    @PostMapping("/merch/manager")
    public Result registerOrEdit(@RequestBody @Validated UserEditRequest editRequest) {
        userService.registerOrEdit(editRequest);
        return Result.ok();
    }

    /**
     * 根据标识查询信息
     */
    @GetMapping("/merch/info")
    public Result queryMerch(String userNo) {
        if (StrUtil.isNotBlank(userNo) && userNo.trim().length() > 10) {
            UserInfo userInfo = userService.queryByUserNo(userNo.trim());
            // 转成 Vo
            UserInfoVo userInfoVo = userConvert.mapInfoVo(userInfo);
            System.out.println(userInfoVo);
            return Result.ok(userInfoVo);
        }
        return Result.fail(SysCode.REQUEST_PARAM_ERROR);
    }

    /**
     * 商户名称的模糊查询
     */
    @GetMapping("/merch/match")
    public Result queryShowName(String shopName) {
        // 前端至少输入两个字符进行模糊查
        if (StrUtil.isNotBlank(shopName) && shopName.trim().length() > 1){
            List<UserInfo> userInfoVos = userService.matchShopName(shopName);
//            List<UserInfoVo> userInfoVosList = userConvert.convertListInfoVo(userInfoVos);
            return Result.ok(userInfoVos);
        }
        return Result.fail(SysCode.REQUEST_PARAM_ERROR);
    }
}
